package dryven.util.crypt;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Random;

public class RandomAlphaNumericalString {
	private int length;
	private boolean onlyUppercase;
	
	public RandomAlphaNumericalString(int length, boolean onlyUppercase) {
		super();
		this.length = length;
		this.onlyUppercase = onlyUppercase;
	}

	public RandomAlphaNumericalString(int length) {
		this(length,false);
	}

	public String generate() {
		int size = 10+26;
		if(!onlyUppercase) {
			size+=26;
		}
		ByteBuffer buffer = ByteBuffer.allocate(length);
		Random rnd = new Random();
		
		for(int i=0;i<length;++i) {
			int val = rnd.nextInt(size);
			//digits
			if(val<10) {
				buffer.put((byte)(val+48));
			//uppercase letters
			} else if(val>=10 && val<36) {
				buffer.put((byte)(val-10+65));
			//lowercase letters
			} else {
				buffer.put((byte)(val-36+97));
			}
		}
		buffer.rewind();
		return Charset.defaultCharset().decode(buffer).toString();
	}
}
